package com.kaifamiao.coordinate;

public class BocAccount {

    private String name; // 开户名称
    private long balance; // 账户余额
    private long threshold; // 阈值(少于这个数就要存款了)

    public BocAccount(String name, long balance, long threshold) {
        this.name = name;
        if( balance > 0 ) {
            this.balance = balance;
        }
        if( threshold > 0 ) {
            this.threshold = threshold;
        }
    }

    public synchronized void deposit(long amount) {
        String threadName = Thread.currentThread().getName();
        if ( this.balance < this.threshold ) {
            System.out.printf("当前余额为: %d元，%s开始存款\n", this.balance, threadName );
            this.balance += amount; // 存款
            System.out.printf("%s存款结束，当前余额为: %d\n", threadName, this.balance);
            this.notifyAll(); // 唤醒在此对象的监视器上等待的所有线程
            return;
        }
        try {
            System.out.printf("账上钱够用，%s不必存款\n", threadName);
            System.out.printf("%s线程即将释放同步锁\n", threadName);
            this.wait();
            System.out.printf("%s线程恢复运行\n", threadName);
        } catch ( InterruptedException e ) {
            System.out.printf("exception: %s\n", e.getMessage() );
        }
    }

    public synchronized void withdraw(long amount) {
        String threadName = Thread.currentThread().getName();
        if ( balance >= amount ) {
            System.out.printf("当前余额为: %d元，%s开始取款\n", balance, threadName );
            balance -= amount; // 取款
            System.out.printf("%s取款结束，当前余额为: %d\n", threadName, balance);
            this.notifyAll(); // 唤醒在此对象的监视器上等待的所有线程
            return;
        }
        try {
            System.out.printf("余额不足，%s取钱失败\n", threadName);
            System.out.printf("%s线程即将释放同步锁\n", threadName);
            this.wait();
            System.out.printf("%s线程恢复运行\n", threadName);
        } catch ( InterruptedException e ) {
            System.out.printf("exception: %s\n", e.getMessage() );
        }
    }


}
